<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, computed, watchEffect } from 'vue'
import { ElMessage } from 'element-plus'
import Logo from '../assets/logo.png'

const router = useRouter()
const route = useRoute()

// 登录判断
const isLogin = ref(!!localStorage.getItem('loginUser'))
const loginUser = computed(() => {
  try {
    return JSON.parse(localStorage.getItem('loginUser')) || {}
  } catch { return {} }
})
const userName = computed(() => loginUser.value?.username || '用户')

// 只在非登录页面显示欢迎、退出
const showUser = computed(() => isLogin.value && route.path !== '/login')

function goHome() {
  router.push(isLogin.value ? '/route-list' : '/login')
}
function goLogin() {
  router.push('/login')
}
function logout() {
  localStorage.removeItem('loginUser')
  isLogin.value = false
  ElMessage.success('已退出登录')
  router.push('/login')
  setTimeout(() => location.reload(), 200)
}
</script>

<template>
  <header class="main-header">
    <div class="header-left" @click="goHome">
      <img :src="Logo" class="logo-img" alt="logo" />
      <span class="logo-title">个人学习路线与笔记</span>
    </div>
    <div class="header-right">
      <template v-if="showUser">
        <el-tag effect="plain" class="welcome-tag">
          欢迎 {{ userName }}
        </el-tag>
        <el-button type="danger" @click="logout" size="small" round>退出</el-button>
      </template>
      <template v-else-if="!isLogin && route.path !== '/login'">
        <el-button size="small" type="primary" @click="goLogin" round>登录</el-button>
      </template>
      <!-- 登录页顶部右侧不显示任何内容 -->
    </div>
  </header>
</template>

<style scoped>
.main-header {
  width: 100vw;
  min-width: 320px;
  box-sizing: border-box;
  height: 68px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  box-shadow: 0 2px 10px #e6e9f0;
  padding: 0 48px 0 48px;
  font-family: '微软雅黑', 'PingFang SC', Arial, sans-serif;
  z-index: 1000;
  position: sticky;
  top: 0;
  border-radius: 0 0 18px 18px;
  margin-bottom: 10px;
}
.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  user-select: none;
}
.logo-img {
  width: 40px;
  height: 40px;
  margin-right: 8px;
  object-fit: contain;
}
.logo-title {
  font-size: 1.55rem;
  font-weight: 700;
  color: #13509e;
  letter-spacing: 2px;
}
.header-right {
  display: flex;
  align-items: center;
  gap: 14px;
}
.welcome-tag {
  font-size: 16px;
  color: #1976d2;
  padding: 3px 14px;
  background: #f3f7ff;
  border-radius: 8px;
  border: 1.2px solid #e3eaf7;
  margin-right: 8px;
}
@media (max-width: 700px) {
  .main-header { padding: 0 10px; font-size: 15px; }
  .logo-title { font-size: 1rem; }
  .logo-img { width: 30px; height: 30px; }
  .welcome-tag { font-size: 13px; padding: 3px 9px; }
}
</style>